package cn.lexi.vip.util;

import org.asynchttpclient.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author ycl
 * @since 2016-10-08
 */
@Component
public class AsyncHttpClientHelper {

    @Autowired
    @Qualifier("httpClient")
    private AsyncHttpClient getClient;

    public String get(String getUrl, int maxConn) {
        AsyncHttpClient client = getClient;
        CountDownLatch latch = new CountDownLatch(maxConn);
        ListenableFuture<String> future = get(getUrl, client, latch);

        String json = null;
        try {
            latch.await();
            json = future.get();
//            client.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    private ListenableFuture<String> get(String url, org.asynchttpclient.AsyncHttpClient client, CountDownLatch latch) {
        return client.prepareGet(url)
                .execute(new AsyncCompletionHandler<String>() {
                    @Override
                    public String onCompleted(Response response) throws Exception {
                        if (latch != null) {
                            latch.countDown();
                        }
                        return response.getResponseBody();
                    }
                });
    }

    @PreDestroy
    private void closeClient(){
        try {
            getClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
